import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Col, Row, Space, Switch, Table } from 'antd';
import { ISession, ITarget } from '@/ts/core';
import Banner from '../components/banner';
import type { ColumnsType } from 'antd/es/table';
import SchemaForm from '@/components/SchemaForm';
import { ProFormColumnsType, ProFormInstance } from '@ant-design/pro-components';
import { IPageTemplate } from '@/ts/core/thing/standard/page';
import OpenFileDialog from '@/components/OpenFileDialog';
import { schema } from '@/ts/base';
interface IProps {
  target: ITarget;
  session: ISession;
  id: string;
}
const WebSite: React.FC<IProps> = ({ target, session, id }) => {
  const [isPublic, setIsPublic] = React.useState(false);
  const formRef = useRef<ProFormInstance>();
  const [modelOpen, setModelOpen] = useState<boolean>(false);
  const [templates, setTemplates] = React.useState<any[]>([]);
  const [editItem, setEditItem] = React.useState<schema.XWebsite>({} as any);
  const hasRelationAuth = target.hasRelationAuth();
  useEffect(() => {
    initData();
  }, [target]);

  const initData = () => {
    target.webSiteProvider.loadTabs().then((res) => {
      setTemplates([...res]);
    });
  };

  const ExtraBtn = () => {
    if (!hasRelationAuth) {
      return <></>;
    }
    return (
      <Space>
        <span>是否公开</span>
        <Switch
          className="page-item-switch"
          defaultChecked={isPublic}
          onChange={(v) => setIsPublic(v)}
        />
      </Space>
    );
  };
  // 序号 栏目名称 展示模板 页面模板 备注
  const columns: ColumnsType<schema.XWebsite> = [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
      width: 60,
      render: (_text, _record, index) => index + 1,
    },
    {
      title: '栏目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '关联页面',
      dataIndex: 'linkPage',
      key: 'linkPage',
    },
    {
      title: '渲染方式',
      key: 'renderType',
      dataIndex: 'renderType',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
      width: '30%',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: any) =>
        !hasRelationAuth ? (
          <></>
        ) : (
          <Space size="middle">
            <a
              onClick={() => {
                setEditItem(record);
                setModelOpen(true);
              }}>
              编辑
            </a>
            <a
              onClick={() => {
                target.webSiteProvider
                  .removeTabs(record)
                  .then(() =>
                    setTemplates(templates.filter((item) => item.id !== record.id)),
                  );
              }}>
              删除
            </a>
          </Space>
        ),
    },
  ];
  const ModalForm: React.FC<any> = () => {
    const [selectModal, setSelectModal] = useState(<></>);
    const [selectedFile, setSelectedFile] = useState<IPageTemplate>();

    const columns: ProFormColumnsType<any>[] = [
      {
        title: '栏目名称',
        dataIndex: 'name',
        formItemProps: {
          rules: [{ required: true, message: '栏目名称为必填项' }],
        },
      },
      {
        title: '渲染方式',
        dataIndex: 'renderType',
        valueType: 'select',
        initialValue: '卡片',
        fieldProps: {
          options: ['卡片', '列表'].map((i) => {
            return {
              value: i,
              label: i,
            };
          }),
        },
      },
      {
        title: '关联页面',
        dataIndex: 'linkPage',
        colProps: { span: 24 },
        formItemProps: {
          rules: [{ required: true, message: '关联页面为必填项' }],
        },
        renderFormItem: (_, info, form) => {
          return (
            <>
              <span>{info?.value || '未选择'}</span>
              <Button
                onClick={() => {
                  setSelectModal(
                    <OpenFileDialog
                      multiple={false}
                      title="选择页面"
                      accepts={['页面模板', '商城模板', '视图']}
                      rootKey={target.directory.spaceKey}
                      onOk={async (files) => {
                        if (files[0]) {
                          form.setFieldsValue({
                            linkPage: files[0].name,
                          });
                          setSelectedFile(files[0] as IPageTemplate);
                        }
                        setSelectModal(<></>);
                      }}
                      onCancel={() => setSelectModal(<></>)}
                    />,
                  );
                }}>
                选择页面
              </Button>
            </>
          );
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        valueType: 'textarea',
        colProps: { span: 24 },
      },
    ];
    return (
      <>
        <SchemaForm<any>
          open={modelOpen}
          grid={true}
          title={'栏目设置'}
          formRef={formRef}
          width={640}
          initialValues={editItem}
          columns={columns}
          rowProps={{
            gutter: [24, 0],
          }}
          layoutType="ModalForm"
          onFinish={async (values) => {
            let newTemplateInfo: schema.XWebsite = {
              sort: 999,
              groupName: '',
              ...editItem,
            };
            if (selectedFile) {
              newTemplateInfo = {
                ...editItem,
                typeName: selectedFile.typeName,
                entityId: selectedFile.id,
                applicationId: selectedFile.metadata.directoryId,
                directoryId: selectedFile.metadata.directoryId,
                targetId: selectedFile.directory.target.id,
                spaceId: selectedFile.spaceId,
              };
            }
            target.webSiteProvider
              .updateTabs({
                ...newTemplateInfo,
                ...values,
              })
              .finally(() => initData());
            setModelOpen(false);
          }}
          onOpenChange={(open: boolean) => {
            if (!open) setModelOpen(false);
          }}
        />
        {selectModal}
      </>
    );
  };
  return (
    <>
      <Card title="首页" id={id} className="setting-card" size="small" extra={ExtraBtn()}>
        <Row>
          <Col span={24}>
            <Banner
              session={session}
              target={target}
              title="封面设置"
              bannerkey="webSite"
              multi={false}
              height={140}
            />
          </Col>
        </Row>
        <div className="page-card" title="栏目设置">
          <div className="flex justify-between" style={{ padding: '10px 0' }}>
            <div className="">栏目设置</div>
            <div>
              {hasRelationAuth && (
                <Button
                  type="primary"
                  size="small"
                  ghost
                  onClick={() => setModelOpen(true)}>
                  添加
                </Button>
              )}
            </div>
          </div>

          <Table columns={columns} size="small" dataSource={templates} />
        </div>
        {<ModalForm />}
      </Card>
    </>
  );
};

export default WebSite;
